package person.tanjinfu.jaegerexample;

import io.opentracing.Span;
import io.opentracing.Tracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class JaegerExampleService {
    @Autowired
    private Tracer tracer;
    @Autowired
    private JaegerExampleDao jaegerExampleDao;

    private Random random = new Random();

    public String hello() {
        String stringFromRedis = this.readRedis();
        System.out.println("redisContent:" + stringFromRedis);

        String dbString = this.jaegerExampleDao.readDb();
        System.out.println("dbContent:" + dbString);

        return "hello from Jaeger example service. at: " + LocalDateTime.now();

    }

    private String readRedis() {
        Span parentSpan = SpanUtil.getActiveSpan().orElse(null);
        Span dbSpan = this.tracer.buildSpan("read-redis").asChildOf(parentSpan).start();
        try {
            return this.doReadRedis();
        } finally {
            dbSpan.finish();
        }

    }

    private String doReadRedis() {
        try {
            TimeUnit.MILLISECONDS.sleep(this.random.nextInt(1000));// 模拟访问 redis
            return "something from redis";
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }


}
